﻿//----------------------------------------------------------------------//
//-----------------------------TimerMG(计时器)-------------------------//
//--------------------------------------------------------------------//
//-------------------------------------------------------------------//
//---------------------------------------------Creat By YH----------//
//---------------------------------------------2017.01.03 ---------//
//---------------------------------------------Modify By YH-------//
//---------------------------------------------2023.04.14 -------//
using UnityEngine;
using System.Collections.Generic;
using System;

namespace MT_ToolKit
{
    public class TimerMG : MonoSingleton<TimerMG>
    {
        private static long TimerIdx = 0;
        private static Dictionary<long, TimerData> Timer_Dict = new Dictionary<long, TimerData>();
        private static List<long> Remove_List = new List<long>();

        void Update()
        {
            for (int i = 0; i < Remove_List.Count; i++)
            {
                Timer_Dict.Remove(Remove_List[i]);
            }
            Remove_List.Clear();
            foreach (var item in Timer_Dict)
            {
                if (!item.Value.isComplete)
                {
                    item.Value.SetUpdate();
                }
            }
        }
        public TimerData CreatTimer(float duration)
        {
            TimerIdx++;
            return CreatTimer(duration, TimerIdx);
        }


        /// <summary>
        /// 创建计时器
        /// </summary>
        /// <param name="duration">时间长度</param>
        /// <returns></returns>
        public TimerData CreatTimer(float duration, long idx)
        {
            //Idx++;
            if (Timer_Dict.ContainsKey(idx))
            {
                Debug.LogError("Timer_Dict已包含该Key");
                return null;
            }
            TimerData NewCreat = new TimerData(duration, idx, RemoveTimer);
            Timer_Dict.Add(idx, NewCreat);
            return NewCreat;
        }

        public void RemoveTimer(long idx)
        {
            if (Timer_Dict.ContainsKey(idx))
            {
                Timer_Dict[idx].isComplete = true;
                Remove_List.Add(idx);
            }
        }


        public int GetTime(int id, bool Dell = true)
        {
            if (Timer_Dict.ContainsKey(id))
            {
                int time = (int)Timer_Dict[id]._currTime;
                if (Dell)
                    RemoveTimer(id);
                return time;
            }
            return -1;
        }
    }
}

